//
//  ArrayExtension.swift
//  PassVPN
//
//  Created by yiwanjun on 2018/1/31.
//  Copyright © 2018年 Maynard. All rights reserved.
//

import Foundation

public extension Array {
    
    /// Array 转 Data
    /// - Returns: data
    func jsonData() -> Data?{
        var data: Data? = nil
        do {
             data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
        } catch  {
            return nil
        }
        return data
    }
    
    /// Array 转 jsonString
    /// - Returns: jsonString
    func jsonString() -> String?{
        if let data = self.jsonData(){
            return String.init(bytes: data, encoding: String.Encoding.utf8)
        }else{
            return nil
        }
    }
}

public extension Array where Element == String {
    
    /// Array 装 string，每个元素之前默认加逗号
    /// - Parameter separater: 分隔符
    /// - Returns: string
    func toString(separater: String = ",") -> String{
        var res = ""
        for i in 0..<count {
            res += self[i]
            if i < (count - 1) && res.trim().count > 0{
                res += separater
            }
        }
        return res
    }
}

public extension Array {
    subscript(safe index: Int) -> Element? {
        guard index >= 0, index < self.count else {
            return nil
        }
        return self[index]
    }
}
